import { useEffect, useMemo, useRef, useState } from "react";
import styles from "./index.module.less";
import SearchBox from "@/components/SearchBox";
import { COURSE_STATUS, TABS, TAB_VALUES, getSearchOptions, getTableColumns } from "./constant";
import { Flex, Modal, Space, Tabs, message } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import { map } from "lodash";
import useUrl from "@/hooks/useUrl";
import { deleteCourse, getCategoryList, getCourseList, getModalityList, updateStatus } from "@/api/modules/course";
import { useRequest } from "ahooks";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { timeStamp } from "console";

export default () => {
	const { data: data1 } = useRequest(getModalityList);
	const modalityList = map(data1?.data, item => ({
		...item,
		label: item?.base_course_category_name,
		value: item?.base_course_category_id
	}));
	const { data: data2 } = useRequest(getCategoryList);
	const categoryList = map(data2?.data, item => ({
		...item,
		label: item?.course_menus_name,
		value: item?.course_menus_id
	}));

	const { navigate, query } = useUrl();
	const [params, setParams] = useState({});
	const [tabValueInfo, setTabValueInfo] = useState<any>({
		status: TAB_VALUES.all
	});

	const handleSearch = e => {
		setParams(e);
	};

	const handleRequest = async (params: any, sortInfo) => {
		console.log("============sort:", sortInfo);
		const requestData: any = {
			limit: params.pageSize,
			page: params.current,
			course_id: params?.course_id ?? "",
			keyword: params?.keyword ?? "",
			base_course_category_id: params?.base_course_category_id ?? "",
			course_menus_id: params?.course_menus_id ?? "",
			course_status: tabValueInfo.status
		};

		if (Object.hasOwn(sortInfo, "created_at")) {
			requestData.sortType = "created_at";
			requestData.order = sortInfo.created_at === "descend" ? "DESC" : "ASC";
		}

		const res = await getCourseList(requestData);
		return {
			total: res?.total ?? 0,
			data: res?.data ?? []
		};
	};

	const items = TABS;

	const edit = {
			label: "编辑",
			value: "edit"
		},
		up = {
			label: "上架",
			value: "up"
		},
		down = {
			label: "下架",
			value: "down"
		},
		deleteEnum = {
			label: "删除",
			value: "delete"
		};

	const newColumns = [
		...getTableColumns({ modalityList, categoryList }),
		{
			title: "操作",
			width: 220,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "down":
					case "up":
						const changeFun = (status: number, c?: any) => {
							updateStatus({ course_id: record?.course_id, course_status: status }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("操作成功");
									c?.();
									setParams(e => ({
										...e,
										timeStamp: Date.now()
									}));
								}
							});
						};
						Modal.confirm({
							icon: null,
							title: key === "down" ? "确定下架该模块？" : "确定上架该模块？",
							content: key === "down" ? "下架后该模块将在小程序消失" : `上架后该模块将在小程序显示`,
							closable: true,
							onOk: c => {
								changeFun(key === "down" ? -1 : 1, c);
							}
						});

						break;
					case "delete":
						Modal.confirm({
							icon: null,
							title: "删除提示？",
							content: `确认删除${record?.course_name}吗？`,
							closable: true,
							onOk: c => {
								deleteCourse({ course_id: record?.course_id }).then((res: any) => {
									if (res?.code === RESULT_CODES.SUCCESS) {
										message.success("删除成功");
										c?.();
										setParams(e => ({
											...e,
											timeStamp: Date.now()
										}));
									}
								});
							}
						});
						break;
					case "edit":
						return navigate(`/courseCreate?id=${record?.course_id}`);
				}
			},
			options: (record: any) => {
				return [edit, record?.course_status === COURSE_STATUS.up ? down : up, deleteEnum];
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchOptions(tabValueInfo, { modalityList, categoryList });
	}, [modalityList, categoryList]);

	return (
		<div
			className={cs({
				[styles.container]: true
			})}
		>
			<Tabs
				items={items}
				activeKey={tabValueInfo.status}
				onChange={e => {
					setTabValueInfo({
						status: e
					});
					setParams({});
				}}
			/>
			<SearchBox key={tabValueInfo.status} columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} />

			<SuperTable
				params={{
					...params,
					...tabValueInfo
				}}
				// bordered
				rowKey="order_id"
				columns={newColumns}
				request={handleRequest}
				scroll={{ x: "900" }}
			/>
		</div>
	);
};
